import 'dart:io';
import 'package:dio/dio.dart';
import 'package:easydubbing/pages/preview.dart';
import 'package:easydubbing/utils/FutureDioToken.dart';
import 'package:easydubbing/utils/api.dart';
import 'package:easydubbing/utils/style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tencentplayer/flutter_tencentplayer.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loading_indicator_view/loading_indicator_view.dart';
import 'package:permission_handler/permission_handler.dart';

class UpLoadPage extends StatefulWidget{
  _UpLoadPageState createState() => _UpLoadPageState();
}
class _UpLoadPageState extends State<UpLoadPage>{

  File video;
  TencentPlayerController player;
  bool hasChosen = false;
  bool isPlaying = false;

  Future getVideo() async {
    var video = await ImagePicker.pickVideo(source: ImageSource.gallery);
    setState(() {
      this.video = video;
      if(this.video!=null){
        hasChosen = true;
        player = new TencentPlayerController.file(video.path,playerConfig: PlayerConfig(autoPlay: false));
      }else{
        hasChosen = false;
      }
    });
  }

  void _requestPermissions() async {
    var status = await Permission.storage.status;
    if (status.isGranted) {
      getVideo();
    }else{
      await Permission.storage.request().then((value){
        getVideo();
      });
    }
  }

  Future<bool> _onBackPressed() {
    return showDialog(
        context: context,
        builder: (context) =>
            AlertDialog(
              title: Text('确定取消上传吗?'),
              actions: <Widget>[
                TextButton(
                  child: Text('暂不',style: TextStyle(color: Colors.red),),
                  onPressed: () => Navigator.pop(context, false),
                ),
                TextButton(
                  child: Text('确定',style: TextStyle(color: ProjectColor.deepColor),),
                  onPressed: () => Navigator.pop(context, true),
                ),
              ],
            ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: ExactAssetImage("assets/images/bg1.jpeg"),
            fit: BoxFit.cover
          )
        ),
        child: Row(
          children: [
            Expanded(
                child: Column(
                  children: [
                    Expanded(
                        child:Container(
                          child: Column(
                            children: [
                              Spacer(),
                              hasChosen?Spacer():SizedBox(),
                              SizedBox(height: 10,),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Spacer(),
                                  Container(
                                    width: 120,
                                    height: 70,
                                    decoration: BoxDecoration(
                                        color: Colors.grey,
                                        borderRadius: BorderRadius.all(Radius.circular(5)),
                                        image: DecorationImage(
                                            image: ExactAssetImage("assets/images/folks.png"),
                                            fit: BoxFit.cover
                                        )
                                    ),
                                  ),
                                  Spacer(),
                                  Container(
                                    width: 120,
                                    height: 70,
                                    decoration: BoxDecoration(
                                        color: Colors.grey,
                                        borderRadius: BorderRadius.all(Radius.circular(5)),
                                        image: DecorationImage(
                                            image: ExactAssetImage("assets/images/rapper.png"),
                                            fit: BoxFit.cover
                                        )
                                    ),
                                  ),
                                  Spacer(),
                                ],
                              ),
                              SizedBox(height: 10,),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Spacer(),
                                  Container(
                                    width: 120,
                                    height: 70,
                                    decoration: BoxDecoration(
                                        color: Colors.grey,
                                        borderRadius: BorderRadius.all(Radius.circular(5)),
                                        image: DecorationImage(
                                            image: ExactAssetImage("assets/images/country.png"),
                                            fit: BoxFit.cover
                                        )
                                    ),
                                  ),
                                  Spacer(),
                                  Container(
                                    width: 120,
                                    height: 70,
                                    decoration: BoxDecoration(
                                        color: Colors.grey,
                                        borderRadius: BorderRadius.all(Radius.circular(5)),
                                        image: DecorationImage(
                                            image: ExactAssetImage("assets/images/electric.png"),
                                            fit: BoxFit.cover
                                        )
                                    ),
                                  ),
                                  Spacer(),
                                ],
                              ),
                              SizedBox(height: 10,),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Spacer(),
                                  Container(
                                    width: 120,
                                    height: 70,
                                    decoration: BoxDecoration(
                                        color: Colors.grey,
                                        borderRadius: BorderRadius.all(Radius.circular(5)),
                                        image: DecorationImage(
                                            image: ExactAssetImage("assets/images/jazz.png"),
                                            fit: BoxFit.cover
                                        )
                                    ),
                                  ),
                                  Spacer(),
                                  Container(
                                    width: 120,
                                    height: 70,
                                    decoration: BoxDecoration(
                                        color: Colors.grey,
                                        borderRadius: BorderRadius.all(Radius.circular(5)),
                                        image: DecorationImage(
                                            image: ExactAssetImage("assets/images/rock.png"),
                                            fit: BoxFit.cover
                                        )
                                    ),
                                  ),
                                  Spacer(),
                                ],
                              ),
                              SizedBox(height: 10,),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Spacer(),
                                  Container(
                                    width: 120,
                                    height: 70,
                                    decoration: BoxDecoration(
                                        color: Colors.grey,
                                        borderRadius: BorderRadius.all(Radius.circular(5)),
                                        image: DecorationImage(
                                            image: ExactAssetImage("assets/images/classic.png"),
                                            fit: BoxFit.cover
                                        )
                                    ),
                                  ),
                                  Spacer(),
                                  Container(
                                    width: 120,
                                    height: 70,
                                    decoration: BoxDecoration(
                                        color: Colors.grey,
                                        borderRadius: BorderRadius.all(Radius.circular(5)),
                                        image: DecorationImage(
                                            image: ExactAssetImage("assets/images/pure.png"),
                                            fit: BoxFit.cover
                                        )
                                    ),
                                  ),
                                  Spacer(),
                                ],
                              ),
                              SizedBox(height: 10,),
                              Text("异曲同工海量音乐库",style: TextStyle(
                                  color: Colors.white,fontSize: 22,fontWeight: FontWeight.bold
                              ),),
                              SizedBox(height: 10,),
                              Text("上传视频智能配乐",style: TextStyle(
                                  color: Colors.white,fontSize: 16
                              ),),
                              SizedBox(height: 10,),
                              hasChosen?Stack(
                                children: [
                                  Container(
                                    height: 200,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(Radius.circular(5)),
                                      color: Colors.black38,
                                    ),
                                    margin: EdgeInsets.only(left: 12,right: 12,top: 10),
                                    child: Center(
                                      child: AspectRatio(
                                        aspectRatio: player.value.initialized?player.value.aspectRatio:1.5,
                                        child: TencentPlayer(
                                            player
                                        ),
                                      ),
                                    ),
                                  ),
                                  !isPlaying?Container(
                                    margin: EdgeInsets.only(top: 90),
                                    alignment: Alignment.center,
                                    child: ClipOval(
                                      child: Container(
                                        height: 45,
                                        width: 45,
                                        color: Color(0x6f000000),
                                        padding: EdgeInsets.only(left: 3),
                                        child: Icon(Icons.play_arrow_rounded,size: 35,color: Colors.white,),
                                      ),
                                    ),
                                  ): SizedBox(),
                                  Container(
                                    height: 220,
                                    child: GestureDetector(
                                      onTap: (){
                                        if(!player.value.initialized){
                                          player.initialize().then((value) {
                                            setState(() {{
                                              player.play();
                                              isPlaying = true;
                                            }
                                            });
                                          });
                                          return;
                                        }
                                        if(player.value.isPlaying){
                                          setState(() {
                                            isPlaying = false;
                                            player.pause();
                                          });
                                        }
                                        else
                                          setState(() {
                                            isPlaying = true;
                                            player.play();
                                          });
                                      },
                                    ),
                                  ),
                                ],
                              ):Expanded(
                                  child: Column(
                                    children: [
                                      InkWell(
                                        onTap: ()=>_requestPermissions(),
                                        child: Container(
                                          width:50,
                                          child: Image.asset("assets/icons/uploadProcess.png"),
                                        ),
                                      ),
                                      SizedBox(height: 10,),
                                      Text("点击上传视频",style: TextStyle(
                                          color: Colors.white,fontSize: 12
                                      ),),
                                    ],
                                  )
                              ),
                              hasChosen?Expanded(
                                  child: Row(
                                    children: [
                                      Spacer(),
                                      InkWell(
                                        onTap: ()=>getVideo(),
                                        child:Container(
                                          width: 100,
                                          height: 40,
                                          alignment: Alignment.center,
                                          child: Text("重新选择",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(Radius.circular(20)),
                                              gradient: LinearGradient(
                                                  begin: Alignment.centerLeft,
                                                  end: Alignment.centerRight,
                                                  colors: [
                                                    ProjectColor.deepColor,
                                                    ProjectColor.mainColor,
                                                  ]
                                              )),
                                        ),
                                      ),
                                      SizedBox(width: 10,),
                                      InkWell(
                                        onTap: () async{
                                          player.pause();
                                          BuildContext buildContext = context;
                                          showDialog(
                                              context: buildContext,
                                              barrierDismissible: false,
                                              builder: (buildContext){
                                                return WillPopScope(
                                                    child: AlertDialog(
                                                    shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                                    title: Text('提示'),
                                                    content: Container(
                                                      height: 100,
                                                      child: Column(
                                                        children: [
                                                          Container(
                                                            width: 50,
                                                            height: 50,
                                                            child: Center(
                                                              child: Container(
                                                                width: 50,
                                                                height: 50,
                                                                child: LineSpinFadeLoaderIndicator(
                                                                  ballColor: ProjectColor.mainColor,
                                                                ),
                                                              ),
                                                            ),
                                                          ),
                                                          SizedBox(height: 10,),
                                                          Text("视频正在上传和处理，请耐心等待~")
                                                        ],
                                                      ),
                                                    )
                                                ),
                                                    onWillPop:()=> _onBackPressed()
                                                );
                                              }
                                          );
                                          var video = await MultipartFile.fromFile(
                                            this.video.path,
                                            filename: "video",
                                          );
                                          FormData formData = FormData.fromMap({"video":video});
                                          FutureDio("upload", Api.videoProcess,{
                                            "uid":1
                                          },formData: formData).then((value) {
                                            Navigator.pop(buildContext);
                                            setState(() {
                                              hasChosen = false;
                                              this.video = null;
                                            });
                                            Navigator.push(context,
                                                new MaterialPageRoute(builder: (context) => Preview(url: value.data["data"],)));
                                          });
                                        },
                                        child: Container(
                                          width: 100,
                                          height: 40,
                                          alignment: Alignment.center,
                                          child: Text("下一步",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(Radius.circular(20)),
                                              gradient: LinearGradient(
                                                  begin: Alignment.centerLeft,
                                                  end: Alignment.centerRight,
                                                  colors: [
                                                    ProjectColor.deepColor,
                                                    ProjectColor.mainColor,
                                                  ]
                                              )),
                                        ),
                                      ),
                                      Spacer(),
                                    ],)
                              ):SizedBox(),
                              Spacer(),
                            ],
                          ),
                        )
                    )
                  ],
                ))
          ],
        ),
      ),
    );
  }

}